/**************
Web Server for 2015 Computer & Computational Chemistry Conference

Port:9003
Date: 2014-12-18

**************/

package main

import (
	"db/mongo"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"sendMail"
	"strings"
	"time"
)

type Person struct {
	Name         string
	Passwd       string
	Gender       string
	Title        string
	Organization string
	Tel          string
	Email        string
	Filename     string
	Report       string
	Forum        string
	Hotel        string
	RoomId       string
	RoomCount    string
	Note         string
	RegTime      string
	Fee          string
	Status       string
}

type Person_ln struct {
	Name string
	//Passwd       string
	Gender       string
	Title        string
	Organization string
	Tel          string
	Email        string
	//Filename     string
	//Report       string
	Forum string
	//Hotel        string
	//RoomId       string
	//RoomCount    string
	Note    string
	RegTime string
	//Fee          string
	Status string
}

type Person_ln_abs struct {
	Name string
	//Passwd       string
	//Gender       string
	//Title        string
	Organization string
	Tel          string
	Email        string
	Filename     string
	//Report       string
	Forum string
	//Hotel        string
	//RoomId       string
	//RoomCount    string
	Note    string
	AbsTime string
	//Fee          string
	//Status string
}

type HitList struct {
	Count    int64
	Hit      []Person
	QueryMap map[string][]string
	TotalHit int64
}

type Statis struct {
	MemberCount       int64
	MaleCount         int64
	FemaleCount       int64
	FilenameCount     int64
	FeeNumCount       int64
	NoFeeNumCount     int64
	FeeCount          int64
	OralReportCount   int64
	InviteReportCount int64
	NoReportCount     int64
	PostCount         int64
	ForumCount        int64
	Zdxrg_drdcf       int64
	Zdxrg_srbzf_dz    int64
	Zdxrg_srbzf_hz    int64
	Xzjdjd_drdcf      int64
	Xzjdjd_srbzf_dz   int64
	Xzjdjd_srbzf_hz   int64
	Xzjdjd_srhhbzf_dz int64
	Xzjdjd_srhhbzf_hz int64
	Zjy_srbzf_hz      int64
	Zxyd              int64
}

type Admin struct {
	USERNAME string
	PASSWORD string
	STATUS   string
}

func handler(w http.ResponseWriter, r *http.Request) {
	var contents []byte
	var err error
	if r.URL.Path[1:] == "" {
		contents, err = ioutil.ReadFile("index.html")
	} else if strings.Contains(r.URL.Path[1:], ".css") {
		handlecss(w, r)
	} else {
		contents, err = ioutil.ReadFile(r.URL.Path[1:])
	}
	if err != nil {
		fmt.Fprintf(w, "404")
		return
	}
	fmt.Fprintf(w, "%s\n", contents)
}

func handler2(w http.ResponseWriter, r *http.Request) {
	var contents []byte
	var err error
	if r.URL.Path[1:] == "admins" {
		contents, err = ioutil.ReadFile("admin.html")
	} else if strings.Contains(r.URL.Path[1:], ".css") {
		handlecss(w, r)
	} else {
		contents, err = ioutil.ReadFile(r.URL.Path[1:])
	}
	if err != nil {
		fmt.Fprintf(w, "404")
		return
	}
	fmt.Fprintf(w, "%s\n", contents)
}

func handlecss(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", "text/css")
	contents, err := ioutil.ReadFile(r.URL.Path[1:])
	//log.Println(r.URL.Path[1:] + " by handlerCss")
	if err != nil {
		fmt.Fprintf(w, "404")
		return
	}
	fmt.Fprintf(w, "%s\n", contents)
}

func handlerupload(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		return
	}
	r.ParseForm()
	file, handler, err := r.FormFile("file")
	findError(err)
	t := time.Now().Unix()
	ti := time.Unix(t, 0).String()
	regtime := ti[0:13]
	fmt.Println(regtime)
	f, err := os.Create("uploadfile/" + regtime + handler.Filename)
	findError(err)
	defer f.Close()
	io.Copy(f, file)
	fmt.Println("file:  " + r.Form.Get("file"))
}

func send1(to, truename, forum string) {
	//user := "lingnanpharm2015@163.com"
	//password := "20151205"
	user := "18756931836@163.com"
	password := "1198755490"
	host := "smtp.163.com:25"

	subject := `2015年第一届岭南国际药学大会(` + forum + `)在线注册成功`

	body := `
    <html>
    <body>
	<h4>
    尊敬的` + truename + `:
    </h4>
    <h4>
    &nbsp;&nbsp;您好！您已成功在线注册参加2015年第一届岭南国际药学大会(` + forum + `)。请及时缴纳注册费完成注册，11月11日优惠截止。<br>
	&nbsp;&nbsp;帐号户名：中山大学<br>&nbsp;&nbsp;银行帐号：634057761010<br>&nbsp;&nbsp;开户银行：中国银行广州番禺大学城北区支行。
    </h4>
    <h4>
    &nbsp;&nbsp;详情请登录会议网站 <a href='http://www.lnicps.org/' target='_blank'>www.lnicps.org</a> 查看会议信息。
    </h4>
	<h4>
    2015年第一届岭南国际药学大会组委会
    </h4>
    </body>
    </html>
    `
	s := new(sendMail.Mail)
	err := s.Send(user, password, host, to, subject, body, "html")
	if err != nil {
		fmt.Println("send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("send mail success!")
	}

}

func send1_abs(to, truename, forum string) {
	//user := "lingnanpharm2015@163.com"
	//password := "20151205"
	user := "18756931836@163.com"
	password := "1198755490"
	host := "smtp.163.com:25"

	subject := `2015年第一届岭南国际药学大会(` + forum + `)在线投稿成功`

	body := `
    <html>
    <body>
	<h4>
    尊敬的` + truename + `:
    </h4>
    <h4>
    &nbsp;&nbsp;您好！您已成功在线投稿2015年第一届岭南国际药学大会(` + forum + `)。感谢您对大会的支持。</h4>
    <h4>
    &nbsp;&nbsp;详情请登录会议网站 <a href='http://www.lnicps.org/' target='_blank'>www.lnicps.org</a> 查看会议信息。
    </h4>
	<h4>
    2015年第一届岭南国际药学大会组委会
    </h4>
    </body>
    </html>
    `
	s := new(sendMail.Mail)
	err := s.Send(user, password, host, to, subject, body, "html")
	if err != nil {
		fmt.Println("send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("send mail success!")
	}

}

func sendLN(to string, doc Person_ln) {
	//user := "NSCC2015@126.com"
	//password := "nscc2015@sysu"
	//host := "smtp.126.com:25"

	//lingnanpharm2015@163.com
	//20151205
	user := "18756931836@163.com"
	password := "1198755490"
	//user := "lingnanpharm2015@163.com"
	//password := "20151205"
	host := "smtp.163.com:25"

	subject := doc.Name + `  在线注册`

	body := `
    <html>
    <body>
	<h4>
    ` + `岭南国际药学大会组委会` + `:
    </h4>
    <h4>
    &nbsp;&nbsp;` + doc.Name + `已在线注册参加2015年岭南国际药学会:<strong>` + doc.Forum + `</strong>。
    </h4>
	<table border="1">
	<caption>` + doc.Name + `的注册信息</caption>
	<tr>
	  <th>姓名</th>
	  <td>` + doc.Name + `</td>
	</tr>

	<tr>
	  <th>性别</th>
	  <td>` + doc.Gender + `</td>
	</tr>
	<tr>
	  <th>职称</th>
	  <td>` + doc.Title + `</td>
	</tr>
	<tr>
	  <th>单位</th>
	  <td>` + doc.Organization + `</td>
	</tr>
	<tr>
	  <th>电话</th>
	  <td>` + doc.Tel + `</td>
	</tr>
	<tr>
	  <th>邮箱</th>
	  <td>` + doc.Email + `</td>
	</tr>
	<tr>
	  <th>大会分会</th>
	  <td>` + doc.Forum + `</td>
	</tr>
	<tr>
	  <th>备注</th>
	  <td>` + doc.Note + `</td>
	</tr>
	<tr>
	  <th>注册时间</th>
	  <td>` + doc.RegTime + `</td>
	</tr>
	</table>
    </body>
    </html>
    `
	s := new(sendMail.Mail)
	err := s.Send(user, password, host, to, subject, body, "html")
	if err != nil {
		fmt.Println("send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("send mail success!")
	}

}

func sendLN_abs(to string, doc Person_ln_abs) {
	//user := "NSCC2015@126.com"
	//password := "nscc2015@sysu"
	//host := "smtp.126.com:25"

	//lingnanpharm2015@163.com
	//20151205
	user := "18756931836@163.com"
	password := "1198755490"
	//user := "lingnanpharm2015@163.com"
	//password := "20151205"
	host := "smtp.163.com:25"

	subject := doc.Name + `  在线注册`

	body := `
    <html>
    <body>
	<h4>
    ` + `岭南国际药学大会组委会` + `:
    </h4>
    <h4>
    &nbsp;&nbsp;` + doc.Name + `已在线投稿:<strong>` + doc.Forum + `</strong>。
    </h4>
	<table border="1">
	<caption>` + doc.Name + `的投稿信息</caption>
	<tr>
	  <th>姓名</th>
	  <td>` + doc.Name + `</td>
	</tr>
	<tr>
	  <th>文件名称</th>
	  <td>` + doc.Filename + `</td>
	</tr>
	
	<tr>
	  <th>单位</th>
	  <td>` + doc.Organization + `</td>
	</tr>
	<tr>
	  <th>电话</th>
	  <td>` + doc.Tel + `</td>
	</tr>
	<tr>
	  <th>邮箱</th>
	  <td>` + doc.Email + `</td>
	</tr>
	<tr>
	  <th>大会分会</th>
	  <td>` + doc.Forum + `</td>
	</tr>
	<tr>
	  <th>备注</th>
	  <td>` + doc.Note + `</td>
	</tr>
	<tr>
	  <th>注册时间</th>
	  <td>` + doc.AbsTime + `</td>
	</tr>
	</table>
    </body>
    </html>
    `
	s := new(sendMail.Mail)
	err := s.Send(user, password, host, to, subject, body, "html")
	if err != nil {
		fmt.Println("send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("send mail success!")
	}

}

// Connect to Mongo database
func ConnectMongo() mongo.Conn {

	var conn mongo.Conn
	conn, err := mongo.Dial("localhost")
	if err != nil {
		fmt.Println("--- Error: Fail to connect Mongo ---")
		fmt.Println(err)
		return nil
	}
	return conn
}

func GetCollection(conn mongo.Conn, dbname, collename, username, passwd string) mongo.Collection {

	db := mongo.Database{conn, dbname, mongo.DefaultLastErrorCmd}

	errAuth := db.Authenticate(username, passwd)
	if errAuth != nil {
		fmt.Println("Error: Fail to connnect" + dbname)
		fmt.Println(errAuth)
	}
	c := db.C(collename)
	return c
}

func handlersubmit(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		return
	}
	r.ParseForm()
	formVal := r.Form
	name := formVal.Get("name")
	gender := formVal.Get("gender")
	organization := formVal.Get("organization")
	title := formVal.Get("title")
	tel := formVal.Get("tel")
	email := formVal.Get("email")
	//filename := formVal.Get("filename")
	//report := formVal.Get("report")
	forum := formVal.Get("forum")
	//fee := "0"
	//hotel := formVal.Get("hotel")
	//roomcount := formVal.Get("roomcount")
	note := formVal.Get("note")
	//roomId := "R" + tel //似乎这里的 tel 已经是字符串类型了，不用转换了
	fmt.Printf("tel: %s", tel)
	t := time.Now().Unix()
	ti := time.Unix(t, 0).String()
	regtime := ti[0:16]
	//fmt.Println("filename: " + filename)

	conn := ConnectMongo()
	defer conn.Close()
	c := GetCollection(conn, "LNYX2015", "Member", "liuzh", "lzh@334")
	//
	// 判断是否重复注册
	//

	//d1, err := c.Find(map[string]interface{}{"Name": name, "Passwd": passwd}).Count()
	d2, err := c.Find(map[string]interface{}{"Email": email}).Count()
	d3, err := c.Find(map[string]interface{}{"Tel": tel}).Count()
	if err != nil || d2 > 0 || d3 > 0 {
		fmt.Println(err)
		fmt.Fprintf(w, "%s", "FAIL")
		return
	}

	err = c.Insert(&Person_ln{name, gender, title, organization, tel, email, forum, note, regtime, "OK"})
	if err != nil {
		panic(err)
	}
	fmt.Fprintf(w, "%s", "SUCCESS")

	send1(email, name, forum)

	var doc Person_ln
	err = c.Find(map[string]interface{}{"Tel": tel}).One(&doc)
	fmt.Println("name: " + doc.Name)
	fmt.Println("tel: " + doc.Tel)
	meetType := doc.Forum
	if meetType == "第三届国际工业药学和临床药学研讨会" {
		sendLN("18756931836@163.com", doc)
	} else if meetType == "第二届岭南国际DMPK论坛" {
		sendLN("zhihongliu2011@gmail.com", doc)
	} else if meetType == "第二届全国生物颗粒学术研讨会" {
		sendLN("914086859@qq.com", doc)
	} else if meetType == "2015年岭南药物化学学术年会" {
		sendLN("914086859@qq.com", doc)
	}

}

func handlersubmitAbs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		return
	}
	r.ParseForm()
	formVal := r.Form
	name := formVal.Get("name")
	//gender := formVal.Get("gender")
	organization := formVal.Get("organization")
	//title := formVal.Get("title")
	tel := formVal.Get("tel")
	email := formVal.Get("email")
	filename := formVal.Get("filename")
	//report := formVal.Get("report")
	forum := formVal.Get("forum")
	//fee := "0"
	//hotel := formVal.Get("hotel")
	//roomcount := formVal.Get("roomcount")
	note := formVal.Get("note")
	//roomId := "R" + tel //似乎这里的 tel 已经是字符串类型了，不用转换了
	fmt.Printf("tel: %s", tel)
	t := time.Now().Unix()
	ti := time.Unix(t, 0).String()
	regtime := ti[0:16]
	//fmt.Println("filename: " + filename)

	conn := ConnectMongo()
	defer conn.Close()
	c := GetCollection(conn, "LNYX2015", "Abstract", "liuzh", "lzh@334")
	//
	// 判断是否重复注册
	//

	//d1, err := c.Find(map[string]interface{}{"Name": name, "Passwd": passwd}).Count()
	d2, err := c.Find(map[string]interface{}{"Email": email}).Count()
	d3, err := c.Find(map[string]interface{}{"Tel": tel}).Count()
	if err != nil || d2 > 0 || d3 > 0 {
		fmt.Println(err)
		fmt.Fprintf(w, "%s", "FAIL")
		return
	}

	err = c.Insert(&Person_ln_abs{name, organization, tel, email, filename, forum, note, regtime})
	if err != nil {
		panic(err)
	}
	fmt.Fprintf(w, "%s", "ABS SUCCESS")

	send1_abs(email, name, forum)

	var doc Person_ln_abs
	err = c.Find(map[string]interface{}{"Tel": tel}).One(&doc)
	fmt.Println("name: " + doc.Name)
	fmt.Println("tel: " + doc.Tel)
	meetType := doc.Forum
	if meetType == "第三届国际工业药学和临床药学研讨会" {
		sendLN_abs("18756931836@163.com", doc)
	} else if meetType == "第二届岭南国际DMPK论坛" {
		sendLN_abs("zhihongliu2011@gmail.com", doc)
	} else if meetType == "第二届全国生物颗粒学术研讨会" {
		sendLN_abs("914086859@qq.com", doc)
	} else if meetType == "2015年岭南药物化学学术年会" {
		sendLN_abs("914086859@qq.com", doc)
	}

}

func findError(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func main() {
	http.HandleFunc("/", handler)
	//http.HandleFunc("/admins", handler2)
	http.HandleFunc("/upload", handlerupload)
	http.HandleFunc("/submit", handlersubmit)
	http.HandleFunc("/submitAbs", handlersubmitAbs)
	//http.HandleFunc("/admin", handleradmin)
	//http.HandleFunc("/infor", handlerinfor)
	//http.HandleFunc("/login", handlerlogin)
	//http.HandleFunc("/search", handlersearch)
	//http.HandleFunc("/save", handlersave)
	//http.HandleFunc("/paper", handlerpaper)
	//http.HandleFunc("/room", handlerroom)
	//http.HandleFunc("/statistics", handlerstatistics)
	err := http.ListenAndServe(":7000", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
